
#include <fstream>
#include <sys/time.h>
#include <boost/filesystem.hpp>

#include "ftpMgr.h"



static void write(std::string name, std::string &msg) {
    std::ofstream ofile;
    ofile.open(name, std::ios::binary);
    ofile << msg;
    ofile.close();
}

void ftpMgr::init(const std::string ip, const std::string user, const std::string passwd, bool isSave) {
    m_ip = ip;
    m_user = user;
    m_passwd = passwd;
    m_isSave = isSave;
    m_isInited = true;
    LOG << " FTP: " << m_ip << " " << m_user << " " << m_passwd << std::endl;
}

int ftpMgr::Get2Mem(std::string &strData, const char *path, const camera_t camera, off64_t) {

    if (!m_isInited) {
        std::cout << "CRITICAL ERROR ftp Mgr Not Inited" << std::endl;
        exit(-1);
    }
    ftplib *ftpAgent = NULL;
    {
        boost::mutex::scoped_lock lock(m_ftpHandleMapLock);/// 锁定
        auto iter = m_ftpHandleMap.find(camera.ip);
        if (iter != m_ftpHandleMap.end()) {
            ftpAgent = iter->second;
        } else {
            LOG << " ip : " << camera.ip << " FTP AGENT NOT FOUND CREATE ONE" << std::endl;
        }
    } /// 解锁

    if (ftpAgent == NULL) {
        // 创建新代理
        ftpAgent = new ftplib();
        if (ftpAgent->Connect(m_ip.c_str()) != 1) {
            printf("ftp connect error\n");
            LOG << " NEW FTP AGENT INSERT FAIL at connect for camIP: " << camera.ip << " FTPMGR SIZE:"
                << m_ftpHandleMap.size() << std::endl;
            return -1;
        }
        if (ftpAgent->Login(m_user.c_str(), m_passwd.c_str()) != 1) {
            printf("ftp login error\n");
            LOG << " NEW FTP AGENT INSERT FAIL at login for camIP: " << camera.ip << " FTPMGR SIZE:"
                << m_ftpHandleMap.size() << std::endl;
            return -1;
        }

        {
            boost::mutex::scoped_lock lock(m_ftpHandleMapLock);/// 锁定
            auto iter = m_ftpHandleMap.insert(std::pair<std::string, ftplib *>(camera.ip, ftpAgent));
            if (iter.second) {
                LOG << " NEW FTP AGENT INSERT SUCCESS for camIP: " << camera.ip << " FTPMGR SIZE:"
                    << m_ftpHandleMap.size() << std::endl;
            } else {
                LOG << " NEW FTP AGENT INSERT FAIL for camIP: " << camera.ip << " FTPMGR SIZE:"
                    << m_ftpHandleMap.size() << std::endl;
            }
        } /// 解锁
    }
    int ret = !(ftpAgent->Get2Mem(strData, path, ftplib::binary));
    if (m_isSave) {
        struct timeval t;
        gettimeofday(&t, NULL);
        if (!boost::filesystem::exists("ftpDownload")) {
            boost::filesystem::create_directories("ftpDownload");
        }
        if (boost::filesystem::exists("ftpDownload")) {
            LOG << "SAVING FTP DOWNLOAD SUCCESS" << std::endl;
            write("./ftpDownload/" + std::to_string(t.tv_sec) + "." + std::to_string(t.tv_usec) + ".jpg", strData);
        } else {
            LOG << "SAVING FTP DOWNLOAD FAIL" << std::endl;
        }
    }
    return ret;
}

void ftpMgr::Clear(std::string ip) {
    bool isRemoved = false;
    {
        boost::mutex::scoped_lock lock(m_ftpHandleMapLock);/// 锁定
        std::map<std::string, ftplib *>::iterator iter;
        for (iter = m_ftpHandleMap.begin(); iter != m_ftpHandleMap.end();) {
            if (iter->first == ip) {
                if (iter->second != NULL) {
                    iter->second->Quit();
                    delete iter->second;
                    iter->second = NULL;
                }
                iter = m_ftpHandleMap.erase(iter);
                isRemoved = true;
                LOG << " after FTP MGR REMOVE FTPMGR SIZE: "
                    << m_ftpHandleMap.size();
                break;
            } else {
                iter++;
            }
        }
    } /// 解锁
    if (isRemoved) {
        LOG << " FTP MGR REMOVE SUCCESS and reInit later of camera:" << ip << std::endl;
    } else {
        LOG << " FTP MGR REMOVE FAIL no found agent of camera:" << ip << std::endl;
    }
}